var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var webRouter = require('./web_router');
var apiRouterV0 = require('./api_router_v0')
var pug = require('pug');
var cors = require('cors');
var helmet = require('helmet')//安全
var app = express();
var routes_dev = require('./routers_dev/index');
var config = require('./config');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var _ = require('lodash');
var busboy = require('connect-busboy');
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })


var env = process.env.NODE_ENV || 'development';
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'development';

// view engine setup

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// app.use(favicon(__dirname + '/public/img/favicon.ico'));

//通用中间件
app.use(helmet());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(cookieParser(config.session_secret));
app.use(session({
    secret: config.session_secret,
    store: new RedisStore({
        port: config.redis_port,
        host: config.redis_host,
        db: config.redis_db,
        pass:config.redis_password,
    }),
    resave: false,
    saveUninitialized:false,
}))
app.use(busboy());

//静态资源
app.use('/duimen',express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname,'routers_dev','files')))
app.use('/docs',express.static(path.join(__dirname, 'docs/gen')));
//路由
app.use('/dev', routes_dev);
app.use('/', webRouter);
var backend = require('./routers_dev/backend')
var nb = require('./routers_dev/new-backend')
app.use('/',backend)
app.use('/',nb)
app.use('/api/v0', cors() ,apiRouterV0);

var reportAPI = require('./routers_dev/reportAPI')
app.use('/',reportAPI)
//设置locals
_.assignIn(app.locals,{
    config:config
});


//错误处理
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err,
            title: 'error'
        });
    });
}

app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {},
        title: 'error'
    });
});


module.exports = app;
